package com.surveypark.listener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import com.surveypark.domain.security.Right;
import com.surveypark.service.RightService;


@SuppressWarnings("rawtypes")
@Component
public class IniRightListener implements ApplicationListener, ServletContextAware{

	@Resource
	private RightService rs;
	
	private ServletContext sc;//相当于jsp中的application范围
	
	@Override
	public void onApplicationEvent(ApplicationEvent arg0) {

		//如果监听的是上下文刷新事件表示spring容器已经准备好了
		if(arg0 instanceof ContextRefreshedEvent) {
			List<Right> list = rs.findAllEntities();//查找出所有的权限
			Map<String, Right> map = new HashMap<String, Right>();
			for(Right r : list){
				map.put(r.getRightUrl(), r);//将url与right关联起来
			}
			if(sc != null){
				sc.setAttribute("all_rights_map", map);
			}
		}
	}

	@Override
	public void setServletContext(ServletContext arg0) {//先于onApplicationEvent方法执行

		this.sc = arg0;
	}

}
